package com.easymin.weixin.controller.res;

import com.alibaba.fastjson.JSONObject;
import com.easymin.weixin.common.api.DaijiaApi;
import com.easymin.weixin.entity.WxApplication;
import com.easymin.weixin.manager.SimpleCarPoolManager;
import com.easymin.weixin.manager.WxApplicationManager;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("api/simpleCarPool")
public class SimpleCarPoolRes {
  
  private static final Logger logger = LoggerFactory.getLogger(SimpleCarPoolRes.class);
  
  @Autowired
  private SimpleCarPoolManager simpleCarPoolManager;
  @Autowired
  private WxApplicationManager wxApplicationManager;
  @Autowired
  private DaijiaApi daijiaApi;

  /**
   * 工作车下单.
   * @param roadLineId 路线Id
   * @param bookLat 上车地点纬度
   * @param bookLng 上车地点经度
   * @param bookTime 上车时间
   * @param bookArea 上车地点
   * @param employId 服务人员Id
   * @param employName 服务人员姓名
   * @param employPhone 服务人员电话
   * @param appKey 区分系统
   */
  @RequestMapping(value = {"book"}, method = RequestMethod.POST)
  public @ResponseBody Map<String, Object> book(
      Long roadLineId, Double bookLat, Double bookLng, Long bookTime, String bookArea, 
      Long employId, String employName, String employPhone, String appKey) throws Exception {
    appKey = StringUtils.trimToEmpty(appKey);
    Map<String, Object> map = new HashMap<String, Object>();
    map = simpleCarPoolManager.book(roadLineId, bookLat, bookLng, bookTime, bookArea, employId,
            employName, employPhone, appKey);
    int code = (int) map.get("code");
    if (code == 0) {
      @SuppressWarnings("unchecked")
      Map<String, Object> data = (Map<String, Object>) map.get("data");
      @SuppressWarnings("unchecked")
      List<Long> lists = (List<Long>) data.get("workCarDrivers");
      Long[] divers = new Long[] {};
      if (lists.size() > 0) {
        divers = lists.toArray(divers);
        if (divers.length >= 1) {
          try {
            WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
            daijiaApi.simplecarpool(wxApplication.getAddress(), divers, employId);
          } catch (Exception ex) {
            logger.error(ex.getMessage());
          }
        } else {
          System.err.println("该路线没有工作车");
        }
      }
    }
    return map;
  }

  /**
   * 查询服务人员附近线路.
   * @param lat 服务人员当前地址纬度
   * @param lng 服务人员当前地址经度
   * @param appKey 区分系统
   * @return 多条路线
   */
  @RequestMapping(value = {"roadLines"}, method = RequestMethod.GET)
  public @ResponseBody Map<String, Object> roadLines(
      @RequestParam("lat") Double lat,
      @RequestParam("lng") Double lng,
      @RequestParam("appKey") String appKey) throws Exception {
    appKey = StringUtils.trimToEmpty(appKey);
    Map<String, Object> map = new HashMap<String, Object>();
    map = simpleCarPoolManager.roadLines(lat, lng, appKey);

    return map;
  }

  /**
   * 查询指定线路.
   * @return 一条工作车路线
   */
  @RequestMapping(value = {"roadLine/{roadLineId}"}, method = RequestMethod.GET)
  public @ResponseBody Map<String, Object> roadLine(
      @PathVariable("roadLineId") Long roadLineId,
      @RequestParam("appKey") String appKey) throws Exception {
    appKey = StringUtils.trimToEmpty(appKey);
    Map<String, Object> map = new HashMap<String, Object>();
    map = simpleCarPoolManager.roadLine(roadLineId, appKey);

    return map;
  }

  /**
   * 查询车辆位置.
   * @param carId 车辆Id
   * @param appKey 区分系统
   * @return 一辆工作车
   */
  @RequestMapping(value = {"car/{carId}"}, method = RequestMethod.GET)
  public @ResponseBody Map<String, Object> car(
      @PathVariable("carId") Long carId,
      @RequestParam("appKey") String appKey) throws Exception {
    appKey = StringUtils.trimToEmpty(appKey);
    Map<String, Object> map = new HashMap<String, Object>();
    map = simpleCarPoolManager.car(carId, appKey);
    int code = (int) map.get("code");
    if (code == 0) {
      Long driverId = (Long) map.get("data");
      if (driverId != null && driverId != 0) {
        WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
        JSONObject object = daijiaApi.queryDriverAddress(wxApplication.getAddress(), driverId);
        Boolean success = object.getBoolean("success");
        if (success) {
          String currentAddress = object.getString("currentAddress");
          Double employLat = object.getDouble("employLat");
          Double employLng = object.getDouble("employLng");
          Map<String, Object> data = new HashMap<String, Object>();
          data.put("address", currentAddress);
          data.put("lat", employLat);
          data.put("lng", employLng);
          map.put("data", data);
        } else {
          map.put("code", -1);
          map.put("msg", "该工作车没有指派司机");
          map.put("data", "");
        }
      } else {
        map.put("msg", "该工作车没有指派司机");
      }
    }
    return map;
  }

  /**
   * 根据员工Id查询工作车订单.
   * @param employId 服务人员Id
   * @param appKey 区分系统
   * @return 工作车订单
   */
  @RequestMapping(value = {"books/{employId}"}, method = RequestMethod.GET)
  public @ResponseBody Map<String, Object> books(
      @PathVariable("employId") Long employId,
      @RequestParam("appKey") String appKey) throws Exception {
    appKey = StringUtils.trimToEmpty(appKey);
    Map<String, Object> map = new HashMap<String, Object>();
    map = simpleCarPoolManager.books(employId, appKey);
    return map;
  }

  /**
   * 取消订单.
   * @param bookId 工作车订单Id
   * @param appKey 区分系统
   */
  @RequestMapping(value = {"cancel/{bookId}"}, method = RequestMethod.POST)
  public @ResponseBody Map<String, Object> cancel(
      @PathVariable("bookId") Long bookId,
      @RequestParam("appKey") String appKey) throws Exception {
    appKey = StringUtils.trimToEmpty(appKey);
    Map<String, Object> map = new HashMap<String, Object>();
    map = simpleCarPoolManager.cancel(bookId, appKey);

    @SuppressWarnings("unchecked")
    Map<String, Object> data = (Map<String, Object>) map.get("data");
    @SuppressWarnings("unchecked")
    List<Long> lists = (List<Long>) data.get("drivers");
    String employName = (String) data.get("employName");
    Long[] divers = new Long[] {};

    if (lists.size() > 0) {
      divers = lists.toArray(divers);
      if (divers.length >= 1) {
        try {
          WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
          daijiaApi.simplecarpoolCancel(wxApplication.getAddress(), divers, employName);
        } catch (Exception ex) {
          logger.error(ex.getMessage());
        }
      } else {
        System.err.println("该路线没有工作车");
      }
    }
    return map;
  }
}
